import React, { Component } from 'react'
import { Toast } from 'antd-mobile'
import { API } from '../../utils/api'
import { Flex } from 'antd-mobile'
import {
  List,
  AutoSizer,
  WindowScroller,
  InfiniteLoader,
} from 'react-virtualized'
import { BASE_URL } from '../../utils/url'
import SearchHeader from '../../components/SearchHeader/inedx'

//导入Filter组件
import Filter from './components/Filter'
//导入Sticky组件
import Sticky from '../../components/Sticky'
//导入NoHouse组件
import NoHouse from '../../components/NoHouse'
//导入房屋列表组件
import HouseItem from '../../components/HouseItem'
//导入获取当前城市名的方法
import { getCurrentCity } from '../../utils'
import styles from './index.module.css'

export default class HouseList extends Component {
  state = {
    list: {},
    count: 0,
    //数据是否加载中
    isLoading: false,
  }

  //初始化
  filters = {}
  label = ''
  value = ''

  //获取房屋列表数据
  searchHouseList = async () => {
    Toast.loading('Loading....', 0, null, false)
    this.setState({
      isLoading: true,
    })

    //地区的cityId
    const res = await API.get('/houses', {
      params: {
        cityId: this.value,
        ...this.filters,
        start: 1,
        end: 20,
      },
    })
    Toast.hide()

    const { list, count } = res.data.body

    this.setState({
      list,
      count,
      isLoading: false,
    })

    if (count !== 0) {
      Toast.info(`共找到${this.state.count}套房源`, 2, null, false)
    }
  }

  //接受Filter组件中的筛选条件数据
  onFilter = (filters) => {
    window.scrollTo(0, 0)
    this.filters = filters
    this.searchHouseList()
  }

  async componentDidMount() {
    const { value, label } = await getCurrentCity()
    this.value = value
    this.label = label
    this.searchHouseList()
  }

  //渲染房屋列表数据
  renderHouseLists = ({
    key, // 唯一区别值
    index, // 索引号
    style, // 每行的样式和位置
  }) => {
    const { list } = this.state
    const house = list[index]
    if (!house) {
      return (
        <div key={key} style={style}>
          <p className={styles.loading}></p>
        </div>
      )
    }
    return (
      <HouseItem
        key={key}
        style={style}
        src={BASE_URL + house.houseImg}
        title={house.title}
        desc={house.desc}
        tags={house.tags}
        price={house.price}
        onClick={() => this.props.history.push(`/detail/${house.houseCode}`)}
      ></HouseItem>
    )
  }

  //判断每一行是否加载完成
  isRowLoaded = ({ index }) => {
    return !!this.state.list[index]
  }

  //加载更多行数
  loadMoreRows = ({ startIndex, stopIndex }) => {
    return new Promise((resolve) => {
      API.get('/houses', {
        params: {
          cityId: this.value,
          ...this.filters,
          start: startIndex,
          end: stopIndex,
        },
      }).then((res) => {
        this.setState({
          list: [...this.state.list, ...res.data.body.list],
        })
        resolve()
      })
    })
  }

  //渲染房屋列表
  renderList = () => {
    const { count, isLoading } = this.state
    if (count === 0 && !isLoading) {
      return <NoHouse>没有找到房源数据，请切换搜索条件！</NoHouse>
    }
    return (
      <InfiniteLoader
        isRowLoaded={this.isRowLoaded}
        loadMoreRows={this.loadMoreRows}
        rowCount={this.state.count}
      >
        {({ onRowsRendered, registerChild }) => (
          <WindowScroller>
            {({ height, isScrolling, scrollTop }) => (
              <AutoSizer>
                {({ width }) => (
                  <List
                    onRowsRendered={onRowsRendered}
                    ref={registerChild}
                    autoHeight // 设置高度为 WindowScroller 最终渲染的列表高度
                    width={width} // 视口的宽度
                    height={height} // 视口的高度
                    rowCount={this.state.count} // List列表项的行数
                    rowHeight={120} // 每一行的高度
                    rowRenderer={this.renderHouseLists} // 渲染列表项中的每一行
                    isScrolling={isScrolling}
                    scrollTop={scrollTop}
                  />
                )}
              </AutoSizer>
            )}
          </WindowScroller>
        )}
      </InfiniteLoader>
    )
  }

  render() {
    return (
      <div>
        {/* 导航栏 */}
        <Flex className={styles.header}>
          <i
            className="iconfont icon-back"
            onClick={() => this.props.history.go(-1)}
          ></i>
          <SearchHeader
            curentCityName={this.label}
            className={styles.SearchHeader}
          ></SearchHeader>
        </Flex>

        {/* 条件筛选栏 */}
        <Sticky height={40}>
          <Filter onFilter={this.onFilter}></Filter>
        </Sticky>

        {/* 房屋列表 */}
        <div className={styles.houseItems}>{this.renderList()}</div>
      </div>
    )
  }
}
